package haoji_juc.xujiahuanxing;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: Dome
 * @description:
 * @className: ThreadAlternatePrint
 * @author: rjt99999
 * @version: 1.0.0
 * @create: 2020-08-04 17:50
 **/
public class ThreadAlternatePrint {
    /*
    开启 3 个线程，这三个线程的 ID 分别为A、 B、 C，每个线程将自己的 ID 在屏幕上打印 10 遍，要求输出的结果必须按顺序显示。
如： ABCABCABC…… 依次递归
     */


    public static void main(String[] args) {

        TestPrint testPrint = new TestPrint();

        new Thread(() -> {

            //打印10遍
            for (int i = 0; i < 10; i++) {
                testPrint.loopA(i);

            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                testPrint.loopB(i);

            }
        }, "B").start();
        new Thread(() -> {

            for (int i = 0; i < 10; i++) {

                testPrint.loopC(i);

            }
        }, "C").start();


    }

}

class TestPrint {

    //线程编号
    int number = 1;
    Lock lock = new ReentrantLock();
    //三个锁，控制三个线程
    Condition a1 = lock.newCondition();
    Condition a2 = lock.newCondition();
    Condition a3 = lock.newCondition();


    public void loopA(int a ) {

        lock.lock();


        try {
            //不等于1时，等待，1时打印
            if (number != 1) {

                a1.await();
            }

            System.out.println(Thread.currentThread().getName() + ": A"+a);


            //唤醒第二个打印B，（唤醒一个）
            number = 2;
            a2.signal();


        } catch (InterruptedException e) {

            e.printStackTrace();

        } finally {

            lock.unlock();
        }


    }

    public void loopB(int a ) {

        lock.lock();

        try {
            if (number != 2) {

                a2.await();
            }

            System.out.println(Thread.currentThread().getName() + ": B"+a);

            number = 3;

            a3.signal();


        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

            lock.unlock();
        }


    }

    public void loopC(int a ) {

        lock.lock();

        try {

            if (number != 3) {

                a3.await();
            }

            System.out.println(Thread.currentThread().getName() + ": C"+a);
            System.out.println("============================");


            number = 1;
            a1.signal();


        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {

            lock.unlock();
        }


    }


}
